<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Strings in Visual Basic</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Visual Basic, learn Visual Basic, strings">
<meta name="description" content="This part of the Visual Basic tutorial covers strings.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Strings in Visual Basic</h1>

<p>
In this part of the Visual Basic tutorial, we will work with string data in more detail.  
</p>

<p>
Strings are the most important data types in computer languages. That is why we dedicate
a whole chapter to working with strings in Visual Basic. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>


<h2>First example</h2>

<p>
A <b>string literal</b> is the notation for representing a string value within the text 
of a computer program.
In Visual Basic string literals are enclosed by double quotes. A string in Visual Basic is
a sequence of Unicode characters.
</p>


<pre class="code">
Option Strict On


Module Example

    Sub Main()

        Dim str1 As String = "There are 10"
        Dim str2 As String = " apples"
        
        Console.WriteLine(str1 + str2)
        
        Console.WriteLine("The length of the first string is " _
            + str1.Length.ToString() + " characters")
        
    End Sub

End Module
</pre>

<p>
In the preceding example, we create two string variables.
Then we add them and compute the length of the first string.
</p>

<pre class="explanation">
Dim str1 As String = "There are 10"
</pre>

<p>
A string variable is declared and initiated. 
</p>

<pre class="explanation">
Console.WriteLine(str1 + str2)
</pre>

<p>
Two strings are concatenated. We use the + operator
to add two strings. 
</p>

<pre class="explanation">
Console.WriteLine("The length of the first string is " _
    + str1.Length.ToString() + " characters")
</pre>

<p>
The <code>Length</code> property is used to
determine the length of the string. 
</p>

<pre>
$ ./basics.exe 
There are 10 apples
The length of the first string is 12 characters
</pre>

<p>
Running the example gives this result. 
</p>


<h2>Using quotes</h2>

<p>
Double quotes are used to create a string literal in Visual Basic. What
if we wanted to display quotes, for example in a direct speech?
To print a double quote, it must be preceded by another double quote.
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()

        Console.WriteLine("There are many stars.")
        Console.WriteLine("He said, ""Which one is your favourite?""")

    End Sub

End Module
</pre>

<p>
When printing double quotes to the console, they must be preceded by another
double quote. 
</p>

<pre class="explanation">
Console.WriteLine("He said, ""Which one is your favourite?""")
</pre>

<p>
Here we show, how to print a direct speech to the console. If we
did not use two double quotes, the compiler would be misled. It would
see two consecutive strings. 
</p>

<pre>
$ ./quotes.exe 
There are many stars.
He said, "Which one is your favourite?"
</pre>

<p>
Output. 
</p>

<h2>Multiline strings</h2>

<p>
It is possible to create a multiline string in Visual Basic. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim multiString As String = "I cheated myself" + vbNewLine + _
"like I knew I would" + vbNewLine + _
"I told ya, I was trouble" + vbNewLine + _
"you know that I'm no good"

        Console.WriteLine(multiString)
        
    End Sub

End Module
</pre>

<p>
The example creates a string that spans several lines. We use a line
continuation character, a plus operator and a <code>vbNewLine</code> 
display constant. 
</p>

<pre>
$ ./multiline.exe 
I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good
</pre>

<p>
This text is displayed in four lines. All the text was assigned to 
one string variable.
</p>


<h2>Comparing strings</h2>

<!--<p>
In this section, we will be comparing strings. String comparison
may be more tricky than numerical comparison. <br>
Things work differently when we compare numbers and when strings. 
</p>


<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim str As String = "Quebec"
        
        Console.WriteLine(str = "Quebec")
        Console.WriteLine(str Is "Quebec")
        Console.WriteLine(str Is str)
        
        Dim str2 As String = str.Clone

        Console.WriteLine(str2)
        Console.WriteLine(str = str2)
        Console.WriteLine(str Is str2)

    End Sub

End Module
</pre>

<p>
If you know C/C++ and languages influenced by them,
like Java, C#, Javascript etc, notice, that we do not
compare equality with the popular == operator
but with the = operator.
</p>

<pre class="explanation">
Dim str As String = "Quebec"
</pre>

<p>
We create and initiate a string variable. 
</p>

<pre class="explanation">
Console.WriteLine(str = "Quebec")
Console.WriteLine(str Is "Quebec")
Console.WriteLine(str Is str)
</pre>

<p>
All these return True. The = operator compares the
contents, while the <b class="keyword">Is</b> operator
compares the references. A String in Visual Basic is a
reference data type. The Is operator simply checks, if two
references point into the same place on the Heap. 
</p>

<pre class="explanation">
Dim str2 As String = str.Clone
</pre>

<p>
We create a clone of the string using the
<b class="keyword">Clone</b> method. 
</p>

<pre class="explanation">
Console.WriteLine(str = str2)
</pre>

<p>
This line prints True to the console. 
It is logical, since the contents of the original
string and the cloned one are the same.
</p>

<pre class="explanation">
Console.WriteLine(str Is str2)
</pre>

<p>
This also returns True. However, this is unexpected. 
The str and str2 are two references. One would expect, that
they point to two different strings (althougn with the same value)
on the Heap. The explanation is the compiler optimalization. Compilers
optimize their code by throwing away duplicate values. Since strings
are immutable data types, it is reasonable to believe, that nothing
bad will happen. 
</p>

-->

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Console.WriteLine("12" = "12") 'Returns True
        Console.WriteLine("17" &lt; "9") ' Returns True
        Console.WriteLine("aa" &gt; "ab") ' Returns False

    End Sub

End Module
</pre>

<p>
Comparison operators work differently in a string context. 
</p>

<pre class="explanation">
Console.WriteLine("17" &lt; "9") 'Returns True
</pre>

<p>
17 is not smaller than 9. But when applying &lt; on two strings,
we do not compare numbers. We compare the sorting order of the characters.
1 is before 9 and is therefore has a 'lower position' and the comparison returns
True. 
</p>

<pre class="explanation">
Console.WriteLine("aa" &gt; "ab") ' Returns False
</pre>

<p>
If the first two characters are equal, the operation continues
on the following ones. The a character is before the b, and the
comparison operation returns False. 
</p>

<hr class="btm">

<p>
There is a <code>String.Compare()</code> method, which compares two specified strings
and returns an integer that indicates their relative position in the sort order.
If the returned value is less than zero, the first string is less than the second. If
it returns zero, both strings are equal. Finally, if the returned value is greater than
zero, the first string is greater than the second.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim str1 As String = "Visual Basic"
        Dim str2 As String = "visual basic"
        
        Console.WriteLine(String.Compare(str1, str2, True))
        Console.WriteLine(String.Compare(str1, str2, False))
        
    End Sub

End Module
</pre>

<p>
There is an optional third ignoreCase argument, that determines, if the case
should be honored or not. 
</p>

<pre class="explanation">
Console.WriteLine(String.Compare(str1, str2, True))
</pre>

<p>
Compare two strings and ignore the case. This line prints 0
to the console. 
</p>

<hr class="btm">

<p>
There is a <code>Like</code> operator, which can be used 
for simple regular expression matching. 
</p>

<pre class="code">
Option Strict On

Module Example
 
    Dim words() As String = {"Seven", "even", "Maven", "Amen", "Leven"}

    Sub Main()

        For Each word As String In words
            If word Like "?*even" Then
                Console.WriteLine("{0} matches the pattern", word)
            Else
                Console.WriteLine("{0} does not match the pattern", word)
            End If
        Next

    End Sub

End Module
</pre>

<p>
We have an array of words. We will test these words against the regex pattern.
We will print a message to the console, if the words matches or not. 
</p>

<pre class="explanation">
Dim words() As String = {"Seven", "even", "Maven", "Amen", "Leven"}
</pre>

<p>
This is an array of five words. 
</p>

<pre class="explanation">
For Each word As String In words
    ...
Next
</pre>

<p>
We use the <code>For Each</code> loop to traverse the array.
The current word is stored in the word variable. 
</p>

<pre class="explanation">
If word Like ".*even" Then
    Console.WriteLine("{0} matches the pattern", word)
Else
    Console.WriteLine("{0} does not match the pattern", word)
End If
</pre>

<p>
The "?*even" is a simple regular expression pattern. The ? matches any single character,
the * zero or more characters. We print a message to inform if the
word matches the pattern or not. 
</p>


<h2>String functions</h2>

<p>
Visual Basic has useful built-in functions that 
can be used for working with strings. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim str As String = "Visual Basic"
        
        Dim n As Integer = Len(str)
        Dim l As String = Left(str, 6)
        Dim r As String = Right(str, 5)
        Dim repl As String = Replace(str, "Basic", "form")

        Console.WriteLine("The string has {0} characters", n)
        Console.WriteLine("The Left function returns {0}", l)
        Console.WriteLine("The Right function returs {0}", r)
        Console.WriteLine("The Replace function returns {0}", repl)

    End Sub

End Module
</pre>

<p>
We introduce four string functions in Visual Basic. 
</p>

<pre class="explanation">
Dim n As Integer = Len(str)
</pre>

<p>
The <code>Len()</code> function returns the number of 
characters in a string. 
</p>

<pre class="explanation">
Dim l As String = Left(str, 6)
</pre>

<p>
This call of the <code>Left()</code> function returns
6 characters from the left of the string. In our case, "Visual".  
</p>

<pre class="explanation">
Dim r As String = Right(str, 5)
</pre>

<p>
Here we get 5 characters from the right. 
</p>

<pre class="explanation">
Dim repl As String = Replace(str, "Basic", "form")
</pre>

<p>
Strings are immutable in Visual Basic. When we use the 
<code>Replace()</code> function, we return a new
modified string, in which the first string is replaced with
the second one. 
</p>

<pre>
$ ./strfunc.exe 
The string has 12 characters
The Left function returns Visual
The Right function returs Basic
The Replace function returns Visual form
</pre>

<p>
Running the example gives the preceding result. 
</p>

<hr class="btm">

<p>
The <code>Join()</code> and <code>Split()</code>
functions are very handy functions. 
</p>

<pre class="code">
Option Strict On

Imports System


Module Example

    Sub Main()
    
        Dim items() As String = {"C#", "Visual Basic", "Java", "Perl"}

        Dim langs As String = Join(items, ",")
        Console.WriteLine(langs)
   
        Dim ls() As String = Split(langs, ",")

        For Each lang As String In ls
            Console.WriteLine(lang)
        Next
        
    End Sub

End Module
</pre>

<p>
In our program, we will join and split strings with these two functions.
</p>

<pre class="explanation">
Dim langs As String = Join(items, ",")
</pre>

<p>
All words from the array are joined. We build one string from them.
There will be a comma character between each two words. 
</p>

<pre class="explanation">
Dim ls() As String = Split(langs, ",")
</pre>

<p>
As a reverse operation, we split the langs string. The 
<code>Split()</code> function returns an array of
words, delimited by a character. In our case it is a 
comma character. 
</p>

<pre class="explanation">
For Each lang As String In ls
    Console.WriteLine(lang)
Next
</pre>

<p>
We go through the array and print its elements. 
</p>

<pre>
$ ./joinsplit.exe 
C#,Visual Basic,Java,Perl
C#
Visual Basic
Java
Perl
</pre>

<p>
Output of the example. 
</p>


<h2>String methods</h2>

<p>
Apart from string functions, there are several string methods.
Some of them provide the same functionality. As we have already
mentioned, strings are not primitive data types. They are
reference types. They are objects and these objects have methods,
which can do some work. 
</p>

<pre class="code">
Option Strict On

Imports System


Module Example

    Sub Main()
        
        Dim str As String = "Determination"
    
        Console.WriteLine(str.Contains("e"))
        Console.WriteLine(str.IndexOf("e"))
        Console.WriteLine(str.LastIndexOf("i"))

        Console.WriteLine(str.ToUpper)
        Console.WriteLine(str.ToLower)
        
    End Sub

End Module
</pre>

<p>
We introduce five string methods in the above example. 
</p>

<pre class="explanation">
Console.WriteLine(str.Contains("e"))
</pre>

<p>
The <code>Contains()</code> method returns True
if the string contains a specific character. 
</p>

<pre class="explanation">
Console.WriteLine(str.IndexOf("e"))
</pre>

<p>
The <code>IndexOf</code> returns the first index
of a letter in the string. 
</p>

<pre class="explanation">
Console.WriteLine(str.LastIndexOf("i"))
</pre>

<p>
The <code>LastIndexOf()</code> methods
returns the last index of a letter in a string. 
</p>

<pre class="explanation">
Console.WriteLine(str.ToUpper)
Console.WriteLine(str.ToLower)
</pre>

<p>
Letters of the string are converted to uppercase with 
the <code>ToUpper</code> method and to lowercase
with the <code>ToLower</code> method.
</p>


<pre>
$ ./strmethods.exe 
True
1
10
DETERMINATION
determination
</pre>

<p>
Running the program. 
</p>

<h2>Copy vs Clone</h2>

<p>
We will describe a difference between two methods. Copy and
Clone. The <code>Copy()</code> method creates a new instance 
of String with the same value as a specified String.
The <code>Clone()</code> method returns a reference 
to the string, which is being cloned. It is not an independent 
copy of the string on the Heap. It is another reference on the same
string. 
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()

        Dim str As String = "Visual Basic"
        
        Dim cloned As String = CType(str.Clone(), String)
        Dim copied As String = String.Copy(str)

        Console.WriteLine(str = cloned) ' Prints True
        Console.WriteLine(str = copied) ' Prints True
        
        Console.WriteLine(str Is cloned) ' Prints True
        Console.WriteLine(str Is copied) ' Prints False
        
        
    End Sub

End Module
</pre>

<p>
Our example demonstrates the difference between the two methods. 
</p>

<pre class="explanation">
Dim cloned As String = CType(str.Clone(), String)
Dim copied As String = String.Copy(str)
</pre>

<p>
The string value is cloned and copied. 
</p>

<pre class="explanation">
Console.WriteLine(str = cloned) ' Prints True
Console.WriteLine(str = copied) ' Prints True
</pre>

<p>
The contents of all three strings are the same. 
</p>

<pre class="explanation">
Console.WriteLine(str Is cloned) ' Prints True
Console.WriteLine(str Is copied) ' Prints False
</pre>

<p>
The <code>Is</code> operator compares
the two reference objects. Therefore comparing a
copied string to the original string returns False. 
Because they are two distinct objects. 
</p>

<h2>Formatting strings</h2>

<p>
In the next examples, we will format strings. The .NET
Framework has a feature called <b>composite formatting</b>. 
It is supported by <code>Format()</code> and
<code>WriteLine()</code> methods. A method takes 
a list of objects and a composite format string as input. 
The format string consists of fixed string plus some format items.
These format items are indexed placeholders which correspond to the objects
in the list. 
</p>

<p>
The format item has the following syntax:
</p>

<pre>
{index[,length][:formatString]}
</pre>

<p>
The index component is mandatory. It is a number starting from 0 that refers
to an item from the list of objects. Multiple items can refer to the same element
of the list of objects. An object is ignored, if it is not referenced by a format
item. If we refer outside the bounds of the list of objects, a runtime exception
is thrown. 
</p>

<p>
The length component is optional. It is the minimum number of characters in
the string representation of the parameter. If positive, the parameter is 
right-aligned; if negative, it is left-aligned. If it is specified, 
there must by a colon separating the index and the length. 
</p>

<p>
The formatString is optional. It is a string that formats a value is a 
specific way. It can be used to format dates, times, numbers or enumerations. 
</p>

<p>
Here we show, how to work with length component of the
format items. We print three columns of numbers to the terminal. 
Left, middle and right aligned. 
</p>

<pre class="code">
Option Strict On

Imports System


Module Example

    Dim oranges As Byte = 2 
    Dim apples As Byte = 4
    Dim bananas As Byte = 3

    Sub Main()
    
        Dim str1 As String = "There are {0} oranges, {1} apples and " + _
            "{2} bananas"

        Dim str2 As String = "There are {1} oranges, {2} bananas and " + _
            "{0} apples"
            
        Console.WriteLine(str1, oranges, apples, bananas)
        Console.WriteLine(str2, apples, oranges, bananas)
        
    End Sub

End Module
</pre>

<p>
We print a simple message to the console. We use only index component
of the format item. 
</p>

<pre class="explanation">
Dim str1 As String = "There are {0} oranges, {1} apples and " + _
    "{2} bananas"
</pre>

<p>
The {0}, {1}, and {2} are format items. We specify the index component.
Other components are optional. 
</p>

<pre class="explanation">
Console.WriteLine(str1, oranges, apples, bananas)
</pre>

<p>
Now we put together the composite formatting. We have the string and
the list of objects (oranges, apples, bananas). The {0} format item
refers to the oranges. The <code>WriteLine()</code> method
replaces the {0} format item with the contents of the oranges
variable.  
</p>

<pre class="explanation">
Dim str2 As String = "There are {1} oranges, {2} bananas and " + _
    "{0} apples"
</pre>

<p>
The order of the format items referring to the objects is notation
important. 
</p>

<pre>
$ ./format1.exe 
There are 2 oranges, 4 apples and 3 bananas
There are 2 oranges, 3 bananas and 4 apples
</pre>

<hr class="btm">

<pre class="code">
Option Strict On

Module Example

    Sub Main()
    
        Console.WriteLine("{0}  {1, 12}", _
            "Decimal", "Hexadecimal")

        Console.WriteLine("{0:D}  {1,8:X}", _ 
            502, 546)
        Console.WriteLine("{0:D}  {1,8:X}", _
            345, 765)
        Console.WriteLine("{0:D}  {1,8:X}", _
            320, 654)
        Console.WriteLine("{0:D}  {1,8:X}", _
            120, 834)
        Console.WriteLine("{0:D}  {1,8:X}", _
            620, 454)
        
    End Sub

End Module
</pre>

<p>
We print numbers in a decimal and hexadecimal
format. We also align the numbers using the length
component.
</p>

<pre class="explanation">
Console.WriteLine("{0:D}  {1,8:X}", _ 
    502, 546)
</pre>

<p>
The {0:D} format item specifies, the first item from the
list of supplied objects will be taken and formatted in 
the decimal format. The {1,8:X} format item takes the
second item. Formats it in the hexadecimal format (:X).
And the string length will be 8 characters (,8). Because the
number has only three characters, it is right aligned and
padded with empty strings.  
</p>

<pre>
$ ./format2.exe 
Decimal   Hexadecimal
502       222
345       2FD
320       28E
120       342
620       1C6
</pre>

<p>
Running the example. 
</p>

<hr class="btm">

<p>
The last two examples will format numeric and date data.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Console.WriteLine(String.Format("Number: {0:N}", 126))
        Console.WriteLine(String.Format("Scientific: {0:E}", 126))
        Console.WriteLine(String.Format("Currency: {0:C}", 126))
        Console.WriteLine(String.Format("Percent: {0:P}", 126))
        Console.WriteLine(String.Format("Hexadecimal: {0:X}", 126))
        
    End Sub

End Module
</pre>

<p>
The example demonstrates the standard
formatting specifiers for numbers. Number 126 is printed 
in five different formats; normal, scientific, currency,
percent and hexadecimal. 
</p>

<pre>
$ ./format3.exe 
Number: 126.00
Scientific: 1.260000E+002
Currency: $126.00
Percent: 12,600.00 %
Hexadecimal: 7E
</pre>


<p>
Output.
</p>

<hr class="btm">

<p>
Finally, we will format date and time data. 
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()
    
        Dim today As DateTime = DateTime.Now()

        Console.WriteLine(String.Format("Short date: {0:d}", today))
        Console.WriteLine(String.Format("Login date: {0:D}", today))
        Console.WriteLine(String.Format("Short time: {0:t}", today))
        Console.WriteLine(String.Format("Long time: {0:T}", today))
        Console.WriteLine(String.Format("Month: {0:M}", today))
        Console.WriteLine(String.Format("Year: {0:Y}", today))
        
    End Sub

End Module
</pre>

<p>
The preceding example demonstrates the standard
formatting specifiers for dates. 
</p>

<pre>
$ ./format4.exe 
Short date: 8/18/2010
Login date: Wednesday, August 18, 2010
Short time: 11:29 PM
Long time: 11:29:40 PM
Month: August 18
Year: August, 2010
</pre>

<p>
Output.
</p>


<p>
This part of the Visual Basic tutorial covered strings. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>

<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified August 22, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

